<?php
/*
 * Plugin Name: OSS Upload
 * Version: 4.2.4
 * Description: Upload with Aliyun OSS, with modified OSS Wrapper and fully native image edit function support.
 * Plugin URI: https://www.xiaomac.com/2016121895.html
 * Author: Link
 * Author URI: https://www.xiaomac.com
 * Text Domain: oss-upload
 * Domain Path: /lang
 * Network: true
*/

add_action('init', 'oss_upload_init', 1);
function oss_upload_init() {
    if(!ouop('oss') || !ouop('oss_akey') || !ouop('oss_skey') || !ouop('oss_endpoint') || !ouop('oss_path')) return;
    define('OSS_ACCESS_ID', trim(ouop('oss_akey')));
    define('OSS_ACCESS_KEY', trim(ouop('oss_skey')));
    define('OSS_ENDPOINT', trim(ouop('oss_endpoint')));
    require_once('lib/OSSWrapper.php');
    oss_upload_dir_loader();
}

function ouop($k, $v=null){
    if(!$op = get_option('ouop')) $op = get_site_option('ouop');
    return isset($op[$k]) ? (isset($v) ? $op[$k] == $v : $op[$k]) : '';
}

function oss_upload_dir_loader(){
    add_filter('upload_dir', 'oss_upload_dir');
}

function oss_upload_check_handle(){
    if(!defined('OSS_ACCESS_ID')) return false;
    $action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');
    return in_array($action, array('upload-plugin', 'upload-theme')) ? false : true;
}

function oss_upload_encode($str){
    $str1 = iconv('utf-8', 'gbk//IGNORE', $str);
    $str2 = iconv('gbk', 'utf-8//IGNORE', $str1);
    return $str2 == $str ? $str : iconv('gbk', 'utf-8//IGNORE', $str);
}

function oss_upload_dir($param){
    if(!oss_upload_check_handle()) return $param;
    if(ouop('oss') && ouop('oss_path') && ouop('oss_url')){
        $basedir = trim(ouop('oss_path'), '/');
        if(empty($param['default']) && $param['basedir'] != $basedir) $param['default'] = $param;
        $param['basedir'] = $basedir;
        $param['path'] = $param['basedir'] . $param['subdir'];
        $param['baseurl'] = trim(ouop('oss_url'), '/');
        $param['url'] = $param['baseurl'] . $param['subdir'];
    }
    return $param;
}

add_filter('wp_handle_upload_prefilter', 'oss_upload_handle_upload_prefilter');
function oss_upload_handle_upload_prefilter($file){
    if(!oss_upload_check_handle()) return $file;
    $upload = oss_upload_dir(wp_get_upload_dir());
    $file['name'] = wp_unique_filename($upload['default']['path'], oss_upload_encode($file['name']));
    $file['name'] = wp_unique_filename($upload['path'], oss_upload_encode($file['name']));
    if((isset($file['size']) && $file['size'] >= 1024*1024) || !ouop('oss_editor')){//upload via file
        remove_filter('upload_dir', 'oss_upload_dir');
    }else if(ouop('oss_backup')){//upload via stream
        @copy($file['tmp_name'], $upload['default']['path'].'/'.$file['name']);
    }
    return $file;
}

add_filter('wp_handle_upload', 'oss_upload_handle_upload', 9999, 2);
function oss_upload_handle_upload($file, $context='upload'){
    if(!has_filter('upload_dir', 'oss_upload_dir')){
        oss_upload_handler($file['file']);
        oss_upload_dir_loader();
    }
    return $file;
}

function oss_upload_handler($file, $errdel=true){
    if(!oss_upload_check_handle()) return;
    $upload = oss_upload_dir(wp_get_upload_dir());
    $basedir = explode('/', substr($upload['basedir'].'/', 6), 2);
    $path = str_replace($upload['default']['basedir'].'/', '', $file);
    try{
        $ossw = new ALIOSS;
        $info = $ossw->create_mpu_object($basedir[0], $basedir[1].$path, array('fileUpload'=>$file));
        unset($_SESSION['oss_upload_error']);
        if($info->isOK()) return $upload['basedir'].'/'.$path;
    }catch(Exception $ex){
        if($errdel && @file_exists($file)) @unlink($file);
        $_SESSION['oss_upload_error'] = $file .'<br/>'. $ex->getMessage();
    }
    return false;
}

add_action('after_setup_theme', 'oss_upload_after_setup_theme');
function oss_upload_after_setup_theme(){
    load_plugin_textdomain('oss-upload', false, 'oss-upload/lang');
    if(($width = ouop('oss_size_width')) && ($height = ouop('oss_size_height'))){
        add_theme_support('post-thumbnails');
        set_post_thumbnail_size(intval($width), intval($height), array('center', 'center'));
    }
}

add_action('admin_init', 'oss_upload_admin_init', 1);
function oss_upload_admin_init() {
    register_setting('oss_upload_admin_options_group', 'ouop');
}

add_action('admin_menu', 'oss_upload_admin_menu');
function oss_upload_admin_menu() {
    add_options_page(__('OSS Upload','oss-upload'), __('OSS Upload','oss-upload'), 'manage_options', 'oss-upload', 'oss_upload_options_page');
}

add_filter('plugin_action_links_'.plugin_basename( __FILE__ ), 'oss_upload_settings_link');
function oss_upload_settings_link($links) {
    if(is_multisite() && (!is_main_site() || !is_super_admin())) return $links;
    $osslink = array(oss_upload_link('options-general.php?page=oss-upload', __('Settings','oss-upload')));
    return array_merge($osslink, $links);
}

add_action('update_option_ouop', 'oss_upload_update_options', 10, 3);
function oss_upload_update_options($old, $value, $option){
    if(is_multisite() && (!is_main_site() || !is_super_admin())) return;
    update_site_option($option, $value);
}

function oss_upload_data($key){
    $data = get_plugin_data( __FILE__ );
    return isset($data) && is_array($data) && isset($data[$key]) ? $data[$key] : '';
}

function oss_upload_show_more($cols, $ret=false){
    static $header = array();
    $arr  = get_user_option('managesettings_page_oss-uploadcolumnshidden');
    $hide = (is_array($arr) && in_array($cols, $arr)) ? ' hidden' : '';
    $head = in_array($cols, $header) ? " class='{$cols}" : " id='{$cols}' class='manage-column";
    $out = "{$head} column-{$cols}{$hide}'";
    if(!in_array($cols, $header)) $header[] = $cols;
    if($ret) return $out;
    echo $out;
}

add_filter('manage_settings_page_oss-upload_columns', 'oss_upload_setting_columns');
function oss_upload_setting_columns($cols){
    $cols['_title'] = __('Show More','oss-upload');
    $cols['oss_upload_desc'] = __('Descriptions', 'oss-upload');
    $cols['oss_upload_example'] = __('Examples', 'oss-upload');
    return $cols;
}

function oss_upload_link($url, $text='', $ext=''){
    if(empty($text)) $text = $url;
    $button = stripos($ext, 'button') !== false ? " class='button'" : "";
    $target = stripos($ext, 'blank') !== false ? " target='_blank'" : "";
    $link = "<a href='{$url}'{$button}{$target}>{$text}</a>";
    return stripos($ext, 'p') !== false ? "<p>{$link}</p>" : "{$link} ";
}

function oss_upload_basename($file){
    return basename(parse_url($file, PHP_URL_PATH));
}

add_filter('wp_generate_attachment_metadata', 'oss_upload_generate_metadata', 10, 2);
function oss_upload_generate_metadata($data, $id){
    if(!ouop('oss')) return $data;
    if(!empty($data['file'])){
        oss_upload_delete_thumbnail($id, $data);
        $upload = wp_get_upload_dir();//just in case
        $data['file'] = str_replace($upload['default']['basedir'].'/', '', $data['file']);
    }
    if(!ouop('oss_backup')){
        $file = get_attached_file($id, 1);//unfilter
        if(@file_exists($file)) @unlink($file);
    }
    return $data;
}

add_filter('wp_get_attachment_metadata', 'oss_upload_attachment_metadata', 9999, 2);
function oss_upload_attachment_metadata($data, $id){
    if(!ouop('oss') || empty($data['sizes'])) return $data;
    $service = ouop('oss_service');
    if($service == 2) $data['sizes'] = array();
    $ss = ouop('oss_style_separator') ? ouop('oss_style_separator') : '?x-oss-process=style/';
    foreach ($data['sizes'] as $k => $v){
        if(!isset($v['file'])) break;
        $postfix = $service ? "{$ss}{$k}" : "?x-oss-process=image/resize,m_fill,w_{$v['width']},h_{$v['height']}";
        $data['sizes'][$k]['file'] = oss_upload_basename($data['file']).$postfix;
    }
    return $data;
}

add_filter('wp_get_attachment_url', 'oss_upload_attachment_url', 9999, 2);
function oss_upload_attachment_url($url, $id){
    if(ouop('oss') && ouop('oss_url')){
        $upload = wp_get_upload_dir();
        $find = $upload['default']['baseurl'];
        $replace = $upload['baseurl'];
        $url = str_replace($find, $replace, $url);
        $url = oss_upload_url_fixer($url);
        if(wp_attachment_is_image($id) && ouop('oss_default_style')) $url .= ouop('oss_default_style');
    }
    return $url;
}

add_filter('get_attached_file', 'oss_upload_attached_file', 9999, 2);
function oss_upload_attached_file($file, $id){
    if(ouop('oss') && ouop('oss_path')){
        $upload = wp_get_upload_dir();
        $find = $upload['default']['basedir'];
        $replace = $upload['basedir'];
        $file = str_replace($find, $replace, $file);
    }
    return $file;
}

add_action('delete_attachment', 'oss_upload_delete_attachment');
function oss_upload_delete_attachment($id){
    if(!ouop('oss')) return;
    $arr = array();
    $upload = wp_get_upload_dir();
    $file = get_post_meta($id, '_wp_attached_file', true);
    if($file){
        $file = str_replace($upload['default']['basedir'].'/', '', $file);
        $arr[] = $upload['basedir'].'/'.$file;
        $arr[] = $upload['default']['basedir'].'/'.$file;
        $subdir = dirname($file);
        $file = get_post_meta($id, '_wp_attachment_backup_sizes', true);
        if(!empty($file)){
            foreach ($file as $k => $v){
                $arr[] = $upload['basedir'].'/'.$subdir.'/'.oss_upload_basename($v['file']);
                $arr[] = $upload['default']['basedir'].'/'.$subdir.'/'.oss_upload_basename($v['file']);
            }
        }
    }
    if(!empty($arr)) $arr = array_unique($arr);
    foreach ($arr as $k) { if(@file_exists($k)) @unlink($k); }
    oss_upload_delete_thumbnail($id);
}

function oss_upload_delete_thumbnail($id, $data=array()){
    if(empty($data)) $data = wp_get_attachment_metadata($id, 1);//unfilter
    $upload = wp_get_upload_dir();
    if(empty($data['sizes']) || empty($upload['default'])) return;
    $arr = array();
    foreach ($data['sizes'] as $k => $v){
        if(oss_upload_basename($data['file']) == oss_upload_basename($v['file'])) continue;
        $file = $upload['path'].'/'.oss_upload_basename($v['file']);
        if(@file_exists($file) && @unlink($file)) $arr[] = $file;
        $file = $upload['default']['path'].'/'.oss_upload_basename($v['file']);
        if(@file_exists($file) && @unlink($file)) $arr[] = $file;
    }
    return $arr;
}

add_filter('wp_calculate_image_srcset', 'oss_upload_image_srcset', 999, 5);
function oss_upload_image_srcset($sources, $size_array, $image_src, $meta, $id){
    if(!ouop('oss') || empty($meta['sizes'])) return $sources;
    if(ouop('oss_service', 2)) return array();//wp_get_attachment_image_srcset
    $upload = wp_get_upload_dir();
    if(parse_url(admin_url(), PHP_URL_SCHEME) == 'https'){
        $upload['default']['baseurl'] = set_url_scheme($upload['default']['baseurl'], 'https');
    }
    $find = $upload['default']['baseurl'];
    $replace = $upload['baseurl'];
    foreach ($sources as $k => $v){
        $url = str_replace($find, $replace, $sources[$k]['url']);
        $url = oss_upload_url_fixer($url);
        if(oss_upload_basename($meta['file']) == oss_upload_basename($url)){
            if(ouop('oss_default_style')) $url .= ouop('oss_default_style');
        }
        $sources[$k]['url'] = $url;
    }
    return $sources;
}

function oss_upload_url_fixer($url){
    if($find = trim(ouop('oss_url_find'))){
        $find  = preg_split('/\|\|/', $find);
        $replace  = preg_split('/\|\|/', trim(ouop('oss_url_replace')));
        $url = str_replace($find, $replace, $url);
    }
    return $url;
}

add_filter('wp_image_editors', 'oss_upload_image_editors');
function oss_upload_image_editors($arr){
    if(ouop('oss_editor')){
        $arr = array_diff($arr, array('WP_Image_Editor_GD'));
        array_unshift($arr, 'WP_Image_Editor_GD');  
    }
    return $arr;
}

add_filter('upload_mimes', 'oss_upload_upload_mimes', 99);
function oss_upload_upload_mimes($mimes){
    if($arr = trim(ouop('upload_mimes'))){
        $arr = explode(',', $arr);
        foreach($arr as $k){
            $kv = explode('=', trim($k));
            if(count($kv) == 2) $mimes[trim($kv[0])] = trim($kv[1]);
        }
    }
    return $mimes;
}

add_filter('file_is_displayable_image', 'oss_upload_displayable_image', 10, 2);
function oss_upload_displayable_image($result, $path){
    if(preg_match('/webp$/i', $path)) $result = true; //depends on @getimagesize
    return $result;
}

add_filter('views_upload', 'oss_upload_views_upload');
function oss_upload_views_upload($views){
    $link = oss_upload_link('options-general.php?page=oss-upload', __('OSS Upload','oss-upload'), 'button');
    if(is_super_admin()) $views['actions'] = $link;
    return $views;
}

add_action('current_screen', 'oss_upload_setting_screen');
function oss_upload_setting_screen() {
    $screen = get_current_screen();
    if($screen->id != 'settings_page_oss-upload' || !ouop('oss')) return;
    $css = '<style>.metabox-prefs span {display: inline-block; vertical-align: text-bottom; margin: 1px 0 0 2px; padding: 0 5px; border-radius: 5px; background-color: #ca4a1f; color: #fff; font-size: 10px; line-height: 17px;}</style>';
    $help_content = '<p>'.oss_upload_data('Description').'</p><br/><p>'.
        oss_upload_link('//promotion.aliyun.com/ntms/yunparter/invite.html?userCode=9ufcuiuf&utm_source=9ufcuiuf', __('Aliyun Coupon <span>NEW</span>', 'oss-upload'), 'button,blank').
        oss_upload_link('//promotion.aliyun.com/ntms/act/oss-discount.html?userCode=9ufcuiuf&utm_source=9ufcuiuf', __('OSS Discount <span>HOT</span>', 'oss-upload'), 'button,blank').
        oss_upload_link('//wordpress.org/support/plugin/oss-upload/reviews/', __('Plugin Rating', 'oss-upload'), 'button,blank').
        oss_upload_link(oss_upload_data('PluginURI'), __('Support and Help', 'oss-upload'), 'button,blank').
        oss_upload_link('//www.xiaomac.com/about', __('Contact Me', 'oss-upload'), 'button,blank').
        oss_upload_link('//www.xiaomac.com/tag/work', __('See More Plugins', 'oss-upload'), 'button,blank').'</p>';
    $tool_content = '<p>'.oss_upload_data('Description').'</p><br/><p>'.
        oss_upload_link('?page=oss-upload&settings-updated=clean', __('Clean Thumbnails', 'oss-upload'), 'button').
        oss_upload_link('?page=oss-upload&settings-updated=upload', __('Upload Local Storage', 'oss-upload'), 'button').
        oss_upload_link('?page=oss-upload&settings-updated=sync', __('Sync Missing Attachment', 'oss-upload'), 'button');
    $help_sidebar = $css.'<p><strong>'.__('For more information', 'oss-upload').'</strong></p>'.
        oss_upload_link('//www.aliyun.com/product/oss/', __('Aliyun OSS', 'oss-upload'), 'p,blank').
        oss_upload_link('//oss.console.aliyun.com/index', __('OSS Console', 'oss-upload'), 'p,blank').
        oss_upload_link('//help.aliyun.com/document_detail/32174.html', __('OSS PHP SDK', 'oss-upload'), 'p,blank');
    $screen->add_help_tab(array('id'=>'oss_upload_help', 'title'=>__('About', 'oss-upload'), 'content'=>$help_content));
    $screen->add_help_tab(array('id'=>'oss_upload_tool', 'title'=>__('Tools', 'oss-upload'), 'content'=>$tool_content));
    $screen->set_help_sidebar($help_sidebar);
}

add_action('admin_notices', 'oss_upload_admin_note');
function oss_upload_admin_note(){
    if(isset($_GET['settings-updated'])){
        if(!is_super_admin() || !ouop('oss')) return;
        $ok = false;
        $index = 1;
        if($_GET['settings-updated'] == 'clean'){
            $upload = wp_get_upload_dir();
            try{
                $out = __('Starting...', 'oss-upload')."<br/>\n";
                $files = get_posts(array('post_type'=>'attachment'));
                foreach ($files as $file){
                    if($arr = oss_upload_delete_thumbnail($file->ID)){
                        foreach ($arr as $v){
                            $out .= $index++.". {$v} deleted<br/>\n";
                        }
                    }
                }
                if(isset($_GET['force'])){ //might have thumbnail that wouldnot be deleted
                    $ossw = new ALIOSS;
                    $files = $ossw->read_dir($upload['default']['basedir'], '', true);
                    foreach ($files as $k => $v){
                        $file = $upload['default']['basedir'].'/'.$v['file'];
                        if(preg_match('/\-[0-9]+x[0-9]+\./', $v['file']) && file_is_valid_image($file)){
                            if(@file_exists($file) && @unlink($file)){
                                $out .= $index++.". {$file} deleted<br/>\n";
                            }
                        }
                    }
                }
                if($index == 1){
                    $out = __('No thumbnail found','oss-upload');
                }else{
                    $out .= __('Clean thumbnails done','oss-upload');
                    $ok = true;
                }
            }catch(Exception $ex){
                $out = $ex->getMessage();
            }
        }else if($_GET['settings-updated'] == 'upload'){
            $upload = wp_get_upload_dir();
            $basedir = explode('/', substr($upload['basedir'].'/', 6), 2);
            try{
                $out = __('Starting...', 'oss-upload')."<br/>\n";
                $ossw = new ALIOSS;
                $out .= $ossw->create_mtu_object_by_dir($basedir[0], $upload['default']['basedir'], true);
                $out .= __('Upload local storage to OSS done', 'oss-upload');
                $ok = true;
            }catch(Exception $ex){
                $out = $ex->getMessage();
            }
        }else if($_GET['settings-updated'] == 'sync'){
            $files = get_posts(array('post_type'=>'attachment'));
            $upload = wp_get_upload_dir();
            $out = __('Starting...', 'oss-upload')."<br/>\n";
            foreach ($files as $file){
                $oss = get_attached_file($file->ID);
                $local = str_replace($upload['basedir'], $upload['default']['basedir'], $oss);
                if(@file_exists($local) && !@file_exists($oss) && ($done = oss_upload_handler($local))){
                    $out .= $index++.". {$done} synced<br/>\n";
                }
            }
            if($index == 1){
                $out = __('No attachments need to be synced','oss-upload');
            }else{
                $out .= __('Sync missing attachments to OSS done','oss-upload');
                $ok = true;
            }
        }else if($_GET['settings-updated'] == 'test'){
            try{
                $rnd = md5(time());
                $file = ouop('oss_path').'/oss_upload_'.$rnd.'.txt';
                $try = file_put_contents($file, $rnd);
                if($try == strlen($rnd)){
                    $out = __('Write OK, ','oss-upload');
                    $try = file_get_contents($file);
                    if($try == $rnd){
                        $out .= __('Read OK, ', 'oss-upload');
                        $try = unlink($file);
                        if($try === true){
                            $out .= __('Delete OK', 'oss-upload');
                            $ok = true;
                        }else{
                            throw new RequestCore_Exception($out . __('Delete Error: ', 'oss-upload') . $try);
                        }
                    }else{
                        throw new RequestCore_Exception($out . __('Read Error: ', 'oss-upload') . $try);
                    }
                }else{
                    throw new RequestCore_Exception($out . __('Write Error: ', 'oss-upload') . $try);
                }
            }catch(Exception $ex){
                $out = esc_html($ex->message);
            }
        }
        if(isset($out)) echo '<div class="'. ($ok ? 'updated fade' : 'error') . '"><p>'.$out.'</p></div>';
    }
    if(isset($_SESSION['oss_upload_error'])){
        echo '<div class="error"><p>'.$_SESSION['oss_upload_error'].'</p></div>';
    }
}

function oss_upload_options_page(){?>
    <div class="wrap">
        <h2><?php _e('OSS Upload','oss-upload')?>
            <a class="page-title-action" href="<?php echo oss_upload_data('PluginURI');?>" target="_blank"><?php echo oss_upload_data('Version');?></a>
        </h2>
        <form action="options.php" method="post">
        <?php settings_fields('oss_upload_admin_options_group'); ?>
        <table class="form-table">
        <tr valign="top">
        <th scope="row"><?php _e('Enable','oss-upload')?></th>
        <td>
            <label><input name="ouop[oss]" type="checkbox" value="1" <?php checked(ouop('oss'),1);?> />
            <?php _e('Use OSS as media library storage','oss-upload')?></label>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Access Key','oss-upload')?></th>
        <td>
            <input name="ouop[oss_akey]" size="60" placeholder="Access Key" value="<?php echo ouop('oss_akey')?>" required />
            <?php echo oss_upload_link('https://ak-console.aliyun.com/', '?', 'blank'); ?>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Secret Key','oss-upload')?></th>
        <td>
            <input type="password" name="ouop[oss_skey]" size="60" placeholder="Secret Key" value="<?php echo ouop('oss_skey')?>" required />
            <?php echo oss_upload_link('https://ak-console.aliyun.com/', '?', 'blank'); ?>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Upload Path','oss-upload')?></th>
        <td>
            <input name="ouop[oss_path]" size="60" placeholder="oss://{BUCKET}/{PATH}" value="<?php echo rtrim(ouop('oss_path'), '/');?>" required />
            <?php echo oss_upload_link('https://help.aliyun.com/document_detail/31902.html', '?', 'blank'); ?>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('<code>{PATH}</code> can be empty, with no slash at the end','oss-upload')?></small></p>
            <div <?php oss_upload_show_more('oss_upload_example'); ?>>
            <p><small><code>oss://my-bucket</code></small></p>
            <p><small><code>oss://my-bucket/uploads</code></small></p>
            </div>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Visit URL','oss-upload')?></th>
        <td>
            <input name="ouop[oss_url]" type="url" size="60" placeholder="http://oss.aliyuncs.com/{BUCKET}/{PATH}" value="<?php echo rtrim(ouop('oss_url'), '/');?>" required />
            <?php echo oss_upload_link('https://help.aliyun.com/document_detail/31902.html', '?', 'blank'); ?>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('<code>{PATH}</code> can be empty, <code>{BUCKET}</code> can be directory or domain, also can be https','oss-upload')?></small></p>
            <div <?php oss_upload_show_more('oss_upload_example'); ?>>
            <p><small><code>http://my-bucket.oss-cn-shenzhen.aliyuncs.com</code></small></p>
            <p><small><code>http://my-bucket.oss-cn-shenzhen.aliyuncs.com/uploads</code></small></p>
            <p><small><code>http://www.my-oss-domain.com</code></small></p>
            <p><small><code>http://www.my-oss-domain.com/uploads</code></small></p>
            <p><small><code>https://img.my-oss-domain.com</code></small></p>
            </div>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Upload EndPoint','oss-upload')?></th>
        <td>
            <input name="ouop[oss_endpoint]" size="60" placeholder="oss-{cn-xxxxxx}.aliyuncs.com" value="<?php echo ouop('oss_endpoint')?>" required />
            <?php echo oss_upload_link('https://help.aliyun.com/document_detail/31837.html', '?', 'blank'); ?>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('<code>{BUCKET}</code> not included, can be internal endpoint if your server is in the same area with oss','oss-upload')?></small></p>
            <div <?php oss_upload_show_more('oss_upload_example'); ?>>
            <p><small><code>oss-cn-hangzhou.aliyuncs.com</code></small></p>
            <p><small><code>oss-cn-shenzhen.aliyuncs.com</code></small></p>
            <p><small><code>oss-cn-shanghai.aliyuncs.com</code></small></p>
            <p><small><code>oss-us-west-1.aliyuncs.com</code></small></p>
            <p><small><code>oss-cn-hangzhou-internal.aliyuncs.com</code></small></p>
            </div>
        </td></tr>
        <tr valign="top">
        <th scope="row"></th>
        <td>
            <?php 
            if(ouop('oss') && ouop('oss_akey') && ouop('oss_skey') && ouop('oss_endpoint')){
                echo oss_upload_link('options-general.php?page=oss-upload&settings-updated=test', __('Run a test', 'oss-upload'), 'p,button');
            } ?>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Image Service','oss-upload')?></th>
        <td>
            <p><label><input name="ouop[oss_service]" type="radio" value="0" <?php checked(ouop('oss_service'),0);?> /> <?php _e('Use default resize for thumbnails','oss-upload')?></label>
            <?php echo oss_upload_link('https://help.aliyun.com/document_detail/44688.html', '?', 'blank'); ?></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Simply and most compatible for almost all scenarios','oss-upload')?></small></p>
            <p <?php oss_upload_show_more('oss_upload_example'); ?>><small><code>photo.jpg?x-oss-process=image/resize,m_fill,w_{width},h_{height}</code></small></p><br/>
            <p><label><input name="ouop[oss_service]" type="radio" value="1" <?php checked(ouop('oss_service'),1);?> /> <?php _e('Use customized styles for advanced purpose','oss-upload')?></label>
            <?php echo oss_upload_link('https://help.aliyun.com/document_detail/44687.html', '?', 'blank'); ?></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Complicated and more powerful but require styles setting on your oss','oss-upload')?></small></p>
            <p <?php oss_upload_show_more('oss_upload_example'); ?>><small><code>photo.jpg?x-oss-process=style/{style}</code>: <code>thumbnail</code> <code>medium</code> <code>large</code> <code>medium_large</code> <code>post-thumbnail</code></small></p><br/>
            <p><label><input name="ouop[oss_service]" type="radio" value="2" <?php checked(ouop('oss_service'),2);?> /> <?php _e('Use origin image in all scenarios','oss-upload')?></label></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Not recommended, would filter out thumbnail metadata under special circumstance','oss-upload')?></small></p>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Featured Image', 'oss-upload')?></th>
        <td>
            <p><label>
                <input type="text" name="ouop[oss_size_width]" size="10" value="<?php echo ouop('oss_size_width')?>" /> x
                <input type="text" name="ouop[oss_size_height]" size="10" value="<?php echo ouop('oss_size_height')?>" />
            </label></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Set the featured image dimensions when thumbnails enabled (width x height)', 'oss-upload');?>: <code>800</code> x <code>450</code></small></p>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Default Style', 'oss-upload')?></th>
        <td>
            <p><label><input name="ouop[oss_default_style]" size="60" value="<?php echo ouop('oss_default_style')?>" />
            <?php echo oss_upload_link('https://help.aliyun.com/document_detail/44686.html', '?', 'blank'); ?></label></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Suffix added after full size image for OSS Image Service style','oss-upload')?>: <code>?abc</code> <code>-xyz</code> <code>/123</code></small></p>
            <?php if(ouop('oss_default_style')):?>
            <p <?php oss_upload_show_more('oss_upload_example'); ?>><small><code>photo.jpg<?php echo ouop('oss_default_style');?></code></small></p>
            <?php endif;?>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Style Separator', 'oss-upload')?></th>
        <td>
            <p><label><input name="ouop[oss_style_separator]" size="60" value="<?php echo ouop('oss_style_separator')?>" /> <?php echo oss_upload_link('https://help.aliyun.com/document_detail/48884.html', '?', 'blank'); ?></label></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Custom style separator for OSS Image Service style','oss-upload')?>: <code>-</code> <code>_</code> <code>/</code> <code>!</code></small></p>
            <?php if(ouop('oss_style_separator')):?>
            <p <?php oss_upload_show_more('oss_upload_example'); ?>><small><code>photo.jpg<span style="color:red"><?php echo ouop('oss_style_separator');?></span>thumbnail</code></small></p>
            <?php endif;?>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Upload Mimes', 'oss-upload')?></th>
        <td>
            <p><label><input name="ouop[upload_mimes]" size="60" value="<?php echo ouop('upload_mimes')?>" />
                <?php echo oss_upload_link('https://codex.wordpress.org/Function_Reference/get_allowed_mime_types', '?', 'blank'); ?></label></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Add file extensions and mime types to the allowed upload list','oss-upload')?></small>: <code>webp=image/webp, flac=audio/x-flac</code></p>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('URL Fixer', 'oss-upload')?></th>
        <td>
            <p><label><input name="ouop[oss_url_find]" size="60" value="<?php echo ouop('oss_url_find')?>" /></label></p>
            <p><label><input name="ouop[oss_url_replace]" size="60" value="<?php echo ouop('oss_url_replace')?>" /></label></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Find and replace whatever strings you want to fix the attachment url','oss-upload')?></small>: <code>http||upload</code> <code>https||uploads</code></p>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Editor Class', 'oss-upload')?></th>
        <td>
            <p><label><input name="ouop[oss_editor]" type="checkbox" value="1" <?php checked(ouop('oss_editor'),1);?> />
            <?php _e('Use <code>WP_Image_Editor_GD</code> instead of <code>WP_Image_Editor_Imagick</code>','oss-upload')?></label></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Recommended, check this if error occurred when edit image or can not generate thumbnail metadata','oss-upload')?></small></p>
        </td></tr>
        <tr valign="top">
        <th scope="row"><?php _e('Local Backup', 'oss-upload')?></th>
        <td>
            <p><label><input name="ouop[oss_backup]" type="checkbox" value="1" <?php checked(ouop('oss_backup'),1);?> />
            <?php _e('Duplicate attachment in local storage','oss-upload')?> <small><code>
            <?php
                $upload = wp_get_upload_dir();
                echo isset($upload['default']['basedir']) ? $upload['default']['basedir'] : $upload['basedir'];
            ?>
            </code></small></label></p>
            <p <?php oss_upload_show_more('oss_upload_desc'); ?>><small><?php _e('Not recommended, just make things complicated','oss-upload')?></small></p>
        </td></tr>
        </table>
        <script type="text/javascript">
            jQuery(':password').focus(
                function(){ jQuery(this).get(0).type = 'text'; }
            ).blur(
                function(){ jQuery(this).get(0).type = 'password'; }
            );
            jQuery('.form-table :input:lt(6):gt(2)').blur(function(){
                if(jQuery(this).val().indexOf(jQuery(this).attr('placeholder').substr(0,4))!=0) jQuery(this).val('');
            });
            jQuery('a[href*="settings-updated=clean"]').click(function(){
                return confirm("<?php _e('This action would clean all thumbnails including local and OSS that filename like photo-800x600.png, cannot be undone, comfirm to process?','oss-upload');?>");
            });
            jQuery('a[href*="settings-updated=upload"]').click(function(){
                return confirm("<?php _e('This action would upload local storage directory to OSS, override if file exists, comfirm to process?','oss-upload');?>");
            });
            jQuery('a[href*="settings-updated=sync"]').click(function(){
                return confirm("<?php _e('This action would upload attachment from local storage that missing in OSS, comfirm to process?','oss-upload');?>");
            });
        </script>
        <?php submit_button();?>
    </div>
    <?php
}

?>